# frozen_string_literal: true

require 'spec_helper'

RSpec.describe Gitlab::Email::FailureHandler do
  let(:raw_message) { fixture_file('emails/valid_reply.eml') }
  let(:receiver) { Gitlab::Email::Receiver.new(raw_message) }

  context 'email processing errors' do
    where(:error, :message, :can_retry) do
      [
        [Gitlab::Email::UnknownIncomingEmail, "We couldn't figure out what the email is for", false],
        [Gitlab::Email::SentNotificationNotFoundError, "We couldn't figure out what the email is in reply to", false],
        [Gitlab::Email::ProjectNotFound, "We couldn't find the project", false],
        [Gitlab::Email::EmptyEmailError, "It appears that the email is blank", true],
        [Gitlab::Email::UserNotFoundError, "We couldn't figure out what user corresponds to the email", false],
        [Gitlab::Email::UserBlockedError, "Your account has been blocked", false],
        [Gitlab::Email::UserNotAuthorizedError, "You are not allowed to perform this action", false],
        [Gitlab::Email::NoteableNotFoundError, "The thread you are replying to no longer exists", false],
        [Gitlab::Email::InvalidAttachment, "Could not deal with that", false],
        [Gitlab::Email::InvalidRecordError, "The note could not be created for the following reasons", true],
        [Gitlab::Email::EmailTooLarge, "it is too large", false]
      ]
    end

    with_them do
      it "sends out a rejection email for #{params[:error]}" do
        perform_enqueued_jobs do
          described_class.handle(receiver, error.new(message))
        end

        email = ActionMailer::Base.deliveries.last
        expect(email).not_to be_nil
        expect(email.to).to match_array(["jake@adventuretime.ooo"])
        expect(email.subject).to include("Rejected")
        expect(email.body.parts.last.to_s).to include(message)
      end

      it 'strips out the body before passing to EmailRejectionMailer' do
        mail = Mail.new(raw_message)
        mail.body = nil

        expect(EmailRejectionMailer).to receive(:rejection).with(match(message), mail.encoded, can_retry).and_call_original

        described_class.handle(receiver, error.new(message))
      end
    end
  end

  context 'non-processing errors' do
    where(:error) do
      [
        [Gitlab::Email::AutoGeneratedEmailError.new("")],
        [ActiveRecord::StatementTimeout.new("StatementTimeout")],
        [RateLimitedService::RateLimitedError.new(key: :issues_create, rate_limiter: nil)]
      ]
    end

    with_them do
      it "does not send a rejection email for #{params[:error]}" do
        perform_enqueued_jobs do
          described_class.handle(receiver, error)
        end

        expect(ActionMailer::Base.deliveries).to be_empty
      end
    end
  end
end
